package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.mapper.RoleDirMapper;
import com.mk.model.entity.RoleDirR;
import com.mk.model.request.RoleDirRequest;
import com.mk.model.response.RoleDirResponse;
import com.mk.service.IRoleDirDService;
import com.mk.service.IRoleDirService;
import com.mk.service.IRoleDirWService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 11:45 AM 3/15/18
 */
@Service
public class RoleDirService extends BaseService<RoleDirMapper,RoleDirR> implements IRoleDirService {

    @Autowired
    private IRoleDirWService roleDirWService;
    @Autowired
    private IRoleDirDService roleDirDService;

    @Override
    public RoleDirR save(RoleDirR roleDirR) {
        return super.insert(roleDirR) ? roleDirR : null;
    }

    @Override
    public Boolean changeRoleDir(RoleDirRequest request) {
        if(request == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入需要赋予权限的文件夹信息");
        if(request.getRoleId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入赋予权限的角色信息以及文件夹信息");
        super.delete(new EntityWrapper<RoleDirR>().eq("role_id",request.getRoleId()));
        List<RoleDirR> roleDirRS = new ArrayList<>();
        for (Long rDir : request.getrDirs()) {
            RoleDirR roleDirR = new RoleDirR();
            roleDirR.setRoleId(request.getRoleId());
            roleDirR.setrDir(rDir);
            roleDirRS.add(roleDirR);
        }
        return super.insertBatch(roleDirRS) && roleDirWService.changeRoleWDir(request.getRoleId(),request.getwDirs())
                && roleDirDService.changeRoleDDir(request.getRoleId(),request.getdDirs());
    }

    @Override
    public RoleDirResponse findByRoleId(Long roleId) {
        List<Long> rDirs = baseMapper.findByRoleId(roleId);
        List<Long> wDirs = roleDirWService.findByRoleId(roleId);
        List<Long> dDirs = roleDirDService.findByRoleId(roleId);
        return new RoleDirResponse(rDirs,wDirs,dDirs);
    }

    @Override
    public Boolean deleteByDir(Long dirId) {
        if(super.delete(new EntityWrapper<RoleDirR>()
                .eq("r_dir",dirId))){
            if(roleDirWService.deleteByDir(dirId))
                return roleDirDService.deleteByDir(dirId);
        }
        return Boolean.FALSE;
    }

    @Override
    public RoleDirR findByDir(Long roleId, Long rDir) {
        return super.selectOne(new EntityWrapper<RoleDirR>()
                .eq("role_id",roleId).eq("r_dir",rDir));
    }
}
